package com.tantou.java.structandalgorithm.sort;

import java.util.Arrays;

/**
 * 归并排序
 * https://www.cnblogs.com/chengxiao/p/6194356.html
 */
public class MergeSortTest {

    public static void main(String[] args) {
        int[] nums = {7, 4, 2, 7, 9, 6, 78, 5, 4, 3, 2, 1};
        mergeSort(nums);
        System.out.println(Arrays.toString(nums));
    }

    public static int[] mergeSort(int[] nums) {

        int[] tmp = new int[nums.length];
        mergePart(nums, 0, nums.length - 1, tmp);
        return nums;
    }

    public static void mergePart(int[] nums, int left, int right, int[] tmp) {
        if (left < right) {
            int mid = (left + right) / 2;
            mergePart(nums, left, mid, tmp);
            mergePart(nums, mid + 1, right, tmp);
            merge(nums, left, mid, right, tmp);

        }
    }

    public static void merge(int[] nums, int left, int mid, int right, int[] tmp) {
        int i = left;
        int j = mid + 1;
        int t = 0;
        //把左右2个数组，进行比较，放入临时数组中
        while (i <= mid && j <= right) {
            if (nums[i] < nums[j]) {
                tmp[t] = nums[i];
                t++;
                i++;
            } else {
                tmp[t] = nums[j];
                t++;
                j++;
            }
        }
        //如果左边 数组还有剩余
        while (i <= mid) {
            tmp[t] = nums[i];
            t++;
            i++;
        }
        //如果右边 数组还有剩余
        while (j <= right) {
            tmp[t] = nums[j];
            t++;
            j++;
        }

        t = 0;
        //拷贝回原数组中
        while (left <= right) {
            nums[left++] = tmp[t++];
        }
    }

}
